#include "Thread.hpp"
#include "RingQueue.hpp"
// #include "Task.hpp"
#include <vector>
using namespace ThreadModule;

int cnt = 1;
// 消费者的任务：获取队列元素并打印
void Consumer(RingQueue<int> &bq, const std::string& name)
{
    while (true)
    {
        int data;
        bq.Pop(&data);
        std::cout << name << " Consum data is : " << data << std::endl;
        sleep(1);
        
    }
}

void Productor(RingQueue<int> &bq, const std::string& name)
{
    while (true)
    {
        bq.Push(cnt);
        std::cout << name << " product data is : " << cnt << std::endl;
        cnt++;
        sleep(1);
    }
}

void InitComm(std::vector<Thread<RingQueue<int>>> *threads, int num, RingQueue<int> &bq, func_t<RingQueue<int>> func, const std::string &who)
{
    for (int i = 0; i < num; i++)
    {
        std::string name = who + "_thread-" + std::to_string(i + 1);
        threads->emplace_back(func, bq, name); // 创建一个thread匿名对象并存放到容器中(创建线程)
        // threads->back().Start(); // 执行刚创建线程的任务
    }
}

void InitProductor(std::vector<Thread<RingQueue<int>>> *threads, int num, RingQueue<int> &bq)
{
    InitComm(threads, num, bq, Productor, "Productor");
}

void InitConsumer(std::vector<Thread<RingQueue<int>>> *threads, int num, RingQueue<int> &bq)
{
    InitComm(threads, num, bq, Consumer, "Consumer");
}

void StartAll(std::vector<Thread<RingQueue<int>>> &threads)
{
    for (auto &thread : threads)
    {
        thread.Start();
    }
}

void WaitAllThread(std::vector<Thread<RingQueue<int>>> &threads)
{
    for (auto &thread : threads)
    {
        thread.Join();
    }
}


int main()
{
    RingQueue<int> *bq = new RingQueue<int>(5);
    std::vector<Thread<RingQueue<int>>> threads; // 所有线程引用一个队列

    InitProductor(&threads, 2, *bq);
    InitConsumer(&threads, 4, *bq); // 创建线程

    StartAll(threads); // 执行线程任务

    WaitAllThread(threads); // 等待所有线程
    return 0;
}